package com.hujing;

import java.util.concurrent.atomic.AtomicInteger;

/**
 *  CAS(Compare And Swap)是乐观锁的一种实现方式
 */
public class CAS {

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    public void increment(){
        int expectedValue;
        int newValue;
        do{
            expectedValue = atomicInteger.get();//获取当前值
            newValue = expectedValue +1;//计算新值
        }while (!atomicInteger.compareAndSet(expectedValue,newValue));//CAS操作
    }

    public int get(){
        return atomicInteger.get();
    }

    public static void main(String[] args) {
        CAS cas = new CAS();
        cas.increment();
        System.out.println("value after increment:"+cas.get());
    }
}
